package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Address;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class AddressServiceImpl implements AddressService {

    @Autowired
    private AddressMapper addressMapper;

    @Override
    public List<Address> findList() {
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getUserId, UserHolder.get().getId());
        return addressMapper.selectList(wrapper);
    }

    @Override
    public void save(Address address) {
        //保存到当前用户,根据userid
        address.setUserId(UserHolder.get().getId());
        address.setIsDefault(0);//设置为非默认地址
        addressMapper.insert(address);
    }

    @Override
    public void setDefault(Long id) {
        //1. 将当前用户的所有地址设置为非默认0
        // update address_book set is_default = 0 where user_id = #{登录用户}
        //1-1 设置更新字段
        Address address = new Address();
        address.setIsDefault(0);//非默认地址

        //1-2 设置更新条件
        LambdaUpdateWrapper<Address> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Address::getUserId, UserHolder.get().getId());

        //1-3 执行更新
        //参数一: 更新字段  参数二: 更新条件
        addressMapper.update(address, wrapper);

        //2. 将当前id设置为默认地址
        //update address_book set is_default = 1 where id = #{前端传入的id}
        address.setIsDefault(1);//默认地址
        address.setId(id);
        addressMapper.updateById(address);
    }

    @Override
    public Address findDefault() {
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getUserId,UserHolder.get().getId())
                .eq(Address::getIsDefault,1);
        return addressMapper.selectOne(wrapper);
    }

    @Override
    public Address findById(Long id) {
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getUserId,UserHolder.get().getId())
                .eq(Address::getId,id);
        return addressMapper.selectOne(wrapper);
    }

    @Override
    public void update(Address address) {
        address.setIsDefault(0);
        addressMapper.updateById(address);
    }

    @Override
    public void deleteById(Long ids) {
        addressMapper.deleteById(ids);
    }
}
